/**
 * BuildingManager - 建筑管理器
 * 负责建筑的绘制和动画
 */

// 建筑类型配置
const BUILDING_TYPES = {
  farm: {
    name: '农场',
    icon: '🚜',
    size: { width: 80, height: 80 },
    color: '#8BC34A',
    secondaryColor: '#7CB342',
    animation: 'crops'
  },
  sawmill: {
    name: '伐木场',
    icon: '🪚',
    size: { width: 80, height: 80 },
    color: '#795548',
    secondaryColor: '#6D4C41',
    animation: 'woodpile'
  },
  house: {
    name: '民房',
    icon: '🏠',
    size: { width: 70, height: 70 },
    color: '#FF9800',
    secondaryColor: '#F57C00',
    animation: 'smoke'
  },
  market: {
    name: '市场',
    icon: '🏪',
    size: { width: 90, height: 80 },
    color: '#9C27B0',
    secondaryColor: '#7B1FA2',
    animation: 'merchant'
  },
  school: {
    name: '学校',
    icon: '🏫',
    size: { width: 85, height: 80 },
    color: '#2196F3',
    secondaryColor: '#1976D2',
    animation: 'books'
  }
}

class BuildingManager {
  constructor(ctx) {
    this.ctx = ctx
    this.buildings = []
    this.draggingBuilding = null
    this.dragPreviewPosition = null
  }

  /**
   * 渲染所有建筑
   */
  render(buildings, timestamp) {
    buildings.forEach(building => {
      if (!building.position) {
        // 如果建筑没有位置，分配一个默认位置
        building.position = this.getDefaultPosition(building)
      }
      
      this.drawBuilding(building, timestamp)
      this.drawAnimation(building, timestamp)
    })
  }

  /**
   * 获取默认位置
   */
  getDefaultPosition(building) {
    const index = this.buildings.length
    const col = index % 5
    const row = Math.floor(index / 5)
    
    return {
      x: 100 + col * 120,
      y: 200 + row * 120
    }
  }

  /**
   * 绘制建筑
   */
  drawBuilding(building, timestamp) {
    const config = BUILDING_TYPES[building.id]
    if (!config) return
    
    const { x, y } = building.position
    const { width, height } = config.size
    
    // 绘制阴影
    this.ctx.setFillStyle('rgba(0, 0, 0, 0.2)')
    this.ctx.beginPath()
    this.ctx.ellipse(x + width/2, y + height + 5, width/2, height/6, 0, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 绘制建筑主体（3D效果）
    // 顶部
    this.ctx.setFillStyle(config.color)
    this.ctx.beginPath()
    this.ctx.moveTo(x, y)
    this.ctx.lineTo(x + width, y)
    this.ctx.lineTo(x + width - 10, y - 10)
    this.ctx.lineTo(x - 10, y - 10)
    this.ctx.closePath()
    this.ctx.fill()
    
    // 正面
    this.ctx.setFillStyle(config.secondaryColor)
    this.ctx.fillRect(x, y, width, height)
    
    // 侧面
    this.ctx.setFillStyle(config.color)
    this.ctx.beginPath()
    this.ctx.moveTo(x + width, y)
    this.ctx.lineTo(x + width + 10, y - 10)
    this.ctx.lineTo(x + width + 10, y + height - 10)
    this.ctx.lineTo(x + width, y + height)
    this.ctx.closePath()
    this.ctx.fill()
    
    // 绘制建筑图标
    this.ctx.setFontSize(40)
    this.ctx.setTextAlign('center')
    this.ctx.setTextBaseline('middle')
    this.ctx.fillText(config.icon, x + width/2, y + height/2)
    
    // 绘制等级标识
    this.ctx.setFillStyle('rgba(255, 255, 255, 0.9)')
    this.ctx.fillRect(x + 5, y + 5, 40, 20)
    this.ctx.setFillStyle('#333')
    this.ctx.setFontSize(14)
    this.ctx.setTextAlign('left')
    this.ctx.fillText(`Lv.${building.level}`, x + 10, y + 15)
  }

  /**
   * 绘制动画
   */
  drawAnimation(building, timestamp) {
    const config = BUILDING_TYPES[building.id]
    if (!config) return
    
    switch(config.animation) {
      case 'crops':
        this.drawCropsAnimation(building, timestamp)
        break
      case 'woodpile':
        this.drawWoodpileAnimation(building, timestamp)
        break
      case 'smoke':
        this.drawSmokeAnimation(building, timestamp)
        break
      case 'merchant':
        this.drawMerchantAnimation(building, timestamp)
        break
      case 'books':
        this.drawBooksAnimation(building, timestamp)
        break
    }
  }

  /**
   * 农作物生长动画
   */
  drawCropsAnimation(building, timestamp) {
    const { x, y } = building.position
    const progress = (timestamp % 5000) / 5000
    const cropHeight = progress * 25
    
    // 绘制5个农作物（更多）
    for (let i = 0; i < 5; i++) {
      const cropX = x + 10 + i * 15
      const cropY = y + 65
      const offset = Math.sin(timestamp / 1000 + i) * 2 // 轻微摆动
      
      // 茎
      this.ctx.setFillStyle('#4CAF50')
      this.ctx.fillRect(cropX + offset, cropY - cropHeight, 8, cropHeight)
      
      // 顶部叶子（多层）
      if (cropHeight > 10) {
        this.ctx.setFillStyle('#66BB6A')
        this.ctx.beginPath()
        this.ctx.arc(cropX + 4 + offset, cropY - cropHeight, 6, 0, Math.PI * 2)
        this.ctx.fill()
        
        // 侧叶
        if (cropHeight > 15) {
          this.ctx.beginPath()
          this.ctx.arc(cropX - 2 + offset, cropY - cropHeight + 5, 4, 0, Math.PI * 2)
          this.ctx.fill()
          this.ctx.beginPath()
          this.ctx.arc(cropX + 10 + offset, cropY - cropHeight + 5, 4, 0, Math.PI * 2)
          this.ctx.fill()
        }
      }
      
      // 成熟时的果实
      if (cropHeight > 20) {
        this.ctx.setFillStyle('#FFA726')
        this.ctx.beginPath()
        this.ctx.arc(cropX + 4 + offset, cropY - cropHeight - 3, 3, 0, Math.PI * 2)
        this.ctx.fill()
      }
    }
  }

  /**
   * 木材堆积动画
   */
  drawWoodpileAnimation(building, timestamp) {
    const { x, y } = building.position
    const count = Math.floor((timestamp % 10000) / 2000) + 1
    
    // 绘制木材堆（交错堆叠）
    for (let i = 0; i < Math.min(count, 5); i++) {
      const layer = Math.floor(i / 2)
      const isEven = i % 2 === 0
      
      // 木材颜色变化
      this.ctx.setFillStyle(isEven ? '#8D6E63' : '#A1887F')
      
      if (layer === 0) {
        // 底层横向
        this.ctx.fillRect(x + 10 + (isEven ? 0 : 20), y + 60, 18, 8)
      } else if (layer === 1) {
        // 第二层纵向
        this.ctx.fillRect(x + 15 + (isEven ? 0 : 15), y + 50, 8, 18)
      } else {
        // 顶层横向
        this.ctx.fillRect(x + 12 + (isEven ? 0 : 15), y + 42, 15, 6)
      }
      
      // 木材纹理
      this.ctx.setStrokeStyle('#5D4037')
      this.ctx.setLineWidth(1)
      for (let j = 0; j < 3; j++) {
        this.ctx.beginPath()
        this.ctx.moveTo(x + 12 + i * 12, y + 58 - layer * 10 + j * 3)
        this.ctx.lineTo(x + 22 + i * 12, y + 58 - layer * 10 + j * 3)
        this.ctx.stroke()
      }
    }
    
    // 锯木屑粒子
    if (count > 2) {
      for (let i = 0; i < 5; i++) {
        const particleX = x + 40 + Math.sin(timestamp / 500 + i) * 10
        const particleY = y + 50 + ((timestamp + i * 200) % 1000) / 50
        this.ctx.setFillStyle(`rgba(139, 110, 99, ${1 - ((timestamp + i * 200) % 1000) / 1000})`)
        this.ctx.fillRect(particleX, particleY, 2, 2)
      }
    }
  }

  /**
   * 烟囱冒烟动画
   */
  drawSmokeAnimation(building, timestamp) {
    const { x, y } = building.position
    const { width } = BUILDING_TYPES[building.id].size
    
    // 绘制烟囱
    this.ctx.setFillStyle('#B71C1C')
    this.ctx.fillRect(x + width - 20, y - 15, 10, 20)
    
    // 烟囱顶部
    this.ctx.setFillStyle('#D32F2F')
    this.ctx.fillRect(x + width - 22, y - 15, 14, 3)
    
    // 绘制烟雾粒子（更多，更自然）
    for (let i = 0; i < 6; i++) {
      const offset = (timestamp / 1000 + i * 0.5) % 4
      const smokeY = y - 15 - offset * 15
      const smokeX = x + width - 15 + Math.sin(timestamp / 500 + i) * (offset * 3)
      const smokeSize = 4 + offset * 2.5
      const alpha = Math.max(0, 1 - offset / 4)
      
      this.ctx.setFillStyle(`rgba(200, 200, 200, ${alpha * 0.5})`)
      this.ctx.beginPath()
      this.ctx.arc(smokeX, smokeY, smokeSize, 0, Math.PI * 2)
      this.ctx.fill()
    }
    
    // 窗户灯光（夜晚效果）
    this.ctx.setFillStyle('#FFF9C4')
    this.ctx.fillRect(x + 15, y + 25, 12, 15)
    this.ctx.fillRect(x + 35, y + 25, 12, 15)
    
    // 窗框
    this.ctx.setStrokeStyle('#5D4037')
    this.ctx.setLineWidth(2)
    this.ctx.strokeRect(x + 15, y + 25, 12, 15)
    this.ctx.strokeRect(x + 35, y + 25, 12, 15)
  }

  /**
   * 商人走动动画
   */
  drawMerchantAnimation(building, timestamp) {
    const { x, y } = building.position
    const { width } = BUILDING_TYPES[building.id].size
    
    const progress = (timestamp % 4000) / 4000
    const merchantX = x + 10 + progress * (width - 20)
    const walkCycle = Math.sin(timestamp / 200) * 3
    
    // 绘制商人身体
    this.ctx.setFillStyle('#FFB74D')
    this.ctx.beginPath()
    this.ctx.arc(merchantX, y + 60, 10, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 商人帽子
    this.ctx.setFillStyle('#795548')
    this.ctx.fillRect(merchantX - 8, y + 50, 16, 5)
    this.ctx.beginPath()
    this.ctx.arc(merchantX, y + 50, 6, Math.PI, 0, true)
    this.ctx.fill()
    
    // 腿部行走动画
    this.ctx.setStrokeStyle('#FFB74D')
    this.ctx.setLineWidth(3)
    this.ctx.beginPath()
    this.ctx.moveTo(merchantX, y + 70)
    this.ctx.lineTo(merchantX - 4, y + 78 + walkCycle)
    this.ctx.stroke()
    this.ctx.beginPath()
    this.ctx.moveTo(merchantX, y + 70)
    this.ctx.lineTo(merchantX + 4, y + 78 - walkCycle)
    this.ctx.stroke()
    
    // 手臂（拿着货物）
    this.ctx.beginPath()
    this.ctx.moveTo(merchantX, y + 60)
    this.ctx.lineTo(merchantX + 8, y + 65)
    this.ctx.stroke()
    
    // 货物箱子
    this.ctx.setFillStyle('#8D6E63')
    this.ctx.fillRect(merchantX + 8, y + 63, 8, 8)
    
    // 闪光效果（商品）
    const sparkle = Math.sin(timestamp / 300) * 0.5 + 0.5
    this.ctx.setFillStyle(`rgba(255, 215, 0, ${sparkle})`)
    this.ctx.beginPath()
    this.ctx.arc(merchantX + 12, y + 67, 2, 0, Math.PI * 2)
    this.ctx.fill()
  }

  /**
   * 书本翻页动画
   */
  drawBooksAnimation(building, timestamp) {
    const { x, y } = building.position
    const page = Math.floor((timestamp % 2000) / 500)
    
    // 绘制书架
    this.ctx.setFillStyle('#8D6E63')
    this.ctx.fillRect(x + 15, y + 45, 50, 25)
    
    // 绘制多本书
    const books = [
      { x: 18, color: '#E53935', width: 8 },
      { x: 27, color: '#1E88E5', width: 10 },
      { x: 38, color: '#43A047', width: 9 },
      { x: 48, color: '#FB8C00', width: 12 }
    ]
    
    books.forEach((book, i) => {
      const bookY = y + 50 + (i === page ? Math.sin(timestamp / 200) * 2 : 0)
      
      // 书脊
      this.ctx.setFillStyle(book.color)
      this.ctx.fillRect(x + book.x, bookY, book.width, 18)
      
      // 书页
      this.ctx.setFillStyle('#FFF')
      this.ctx.fillRect(x + book.x + 1, bookY + 1, book.width - 2, 16)
      
      // 书页线条
      this.ctx.setStrokeStyle('rgba(0, 0, 0, 0.2)')
      this.ctx.setLineWidth(1)
      for (let j = 0; j < 3; j++) {
        this.ctx.beginPath()
        this.ctx.moveTo(x + book.x + 2, bookY + 4 + j * 5)
        this.ctx.lineTo(x + book.x + book.width - 2, bookY + 4 + j * 5)
        this.ctx.stroke()
      }
    })
    
    // 飘浮的知识星星
    for (let i = 0; i < 3; i++) {
      const starX = x + 30 + Math.sin(timestamp / 1000 + i * 2) * 15
      const starY = y + 35 - ((timestamp + i * 500) % 1500) / 50
      const alpha = 1 - ((timestamp + i * 500) % 1500) / 1500
      
      this.ctx.setFillStyle(`rgba(255, 215, 0, ${alpha})`)
      this.ctx.setFontSize(12)
      this.ctx.fillText('✨', starX, starY)
    }
  }

  /**
   * 点击检测
   */
  hitTest(x, y, buildings) {
    for (let i = buildings.length - 1; i >= 0; i--) {
      const building = buildings[i]
      const config = BUILDING_TYPES[building.id]
      if (!config || !building.position) continue
      
      const { x: bx, y: by } = building.position
      const { width, height } = config.size
      
      if (x >= bx && x <= bx + width && y >= by && y <= by + height) {
        return {
          ...building,
          ...config
        }
      }
    }
    
    return null
  }

  /**
   * 开始拖拽建筑
   */
  startDrag(building) {
    this.draggingBuilding = building
    this.dragPreviewPosition = { ...building.position }
  }

  /**
   * 更新拖拽位置
   */
  updateDragPosition(position) {
    if (this.draggingBuilding) {
      this.dragPreviewPosition = position
    }
  }

  /**
   * 结束拖拽
   */
  endDrag() {
    this.draggingBuilding = null
    this.dragPreviewPosition = null
  }

  /**
   * 绘制拖拽预览
   */
  drawDragPreview(gridSize = 80) {
    if (!this.draggingBuilding || !this.dragPreviewPosition) return
    
    const config = BUILDING_TYPES[this.draggingBuilding.id]
    if (!config) return
    
    const { x, y } = this.dragPreviewPosition
    const { width, height } = config.size
    
    // 吸附到网格
    const gridX = Math.round(x / gridSize) * gridSize
    const gridY = Math.round(y / gridSize) * gridSize
    
    // 绘制网格高亮
    this.ctx.setFillStyle('rgba(100, 200, 100, 0.3)')
    this.ctx.fillRect(gridX, gridY, gridSize, gridSize)
    
    // 绘制网格边框
    this.ctx.setStrokeStyle('rgba(100, 200, 100, 0.8)')
    this.ctx.setLineWidth(2)
    this.ctx.strokeRect(gridX, gridY, gridSize, gridSize)
    
    // 绘制建筑半透明预览
    this.ctx.setGlobalAlpha(0.6)
    
    // 建筑主体
    this.ctx.setFillStyle(config.color)
    this.ctx.fillRect(gridX, gridY, width, height)
    
    // 建筑边框
    this.ctx.setStrokeStyle(config.secondaryColor)
    this.ctx.setLineWidth(3)
    this.ctx.strokeRect(gridX, gridY, width, height)
    
    // 建筑图标
    this.ctx.setFontSize(32)
    this.ctx.fillText(config.icon, gridX + width/2 - 16, gridY + height/2 + 10)
    
    this.ctx.setGlobalAlpha(1)
    
    // 绘制连接线（从原位置到新位置）
    if (this.draggingBuilding.position) {
      const { x: origX, y: origY } = this.draggingBuilding.position
      
      this.ctx.setStrokeStyle('rgba(100, 200, 100, 0.5)')
      this.ctx.setLineWidth(2)
      this.ctx.setLineDash([5, 5])
      this.ctx.beginPath()
      this.ctx.moveTo(origX + width/2, origY + height/2)
      this.ctx.lineTo(gridX + width/2, gridY + height/2)
      this.ctx.stroke()
      this.ctx.setLineDash([])
    }
  }

  /**
   * 检查位置是否可用
   */
  isPositionAvailable(position, buildings, excludeBuilding = null, gridSize = 80) {
    const gridX = Math.round(position.x / gridSize) * gridSize
    const gridY = Math.round(position.y / gridSize) * gridSize
    
    for (const building of buildings) {
      if (building === excludeBuilding) continue
      if (!building.position || !building.built) continue
      
      const bGridX = Math.round(building.position.x / gridSize) * gridSize
      const bGridY = Math.round(building.position.y / gridSize) * gridSize
      
      if (bGridX === gridX && bGridY === gridY) {
        return false
      }
    }
    
    return true
  }
}

export default BuildingManager
export { BUILDING_TYPES }
